<template>
  <view class="top-nav-filter">
    <!-- 资产-只显示门店筛选 -->
    <block v-if="tabsType == 'asset'">
      <remote-select
        class="top-nav-filter__item active"
        type="site_all"
        multiple
        :slotStatus="true"
        v-model="queryParam.siteIdList"
        @change="onAssetSiteChange"
      >
        <template #remote-select>
          <view class="top-nav-filter__item active">
            <ve-icon name="filterwhite" size="24" class="top-nav-filter__item-icon" />
            <!-- 已选门店数量 > 0 -->
            <block v-if="queryParam.siteIdList.length > 0">
              <text class="top-nav-filter__item-text">已选门店</text>
              <view class="badge">{{ `+${queryParam.siteIdList.length}` }}</view>
            </block>
            <!-- 未选门店则是全部门店 -->
            <block v-else>
              <text class="top-nav-filter__item-text">全部门店</text>
            </block>
          </view>
        </template>
      </remote-select>
    </block>
    <!-- 其他类型 -->
    <block v-else>
      <!-- 循环navList -->
      <view
        v-for="(item, key) in navList"
        :key="item.name"
        class="top-nav-filter__item"
        :class="{ active: item.active }"
        @click="onFilterClick(item, key)"
      >
        <ve-icon v-if="item.active" name="filterwhite" size="24" class="top-nav-filter__item-icon" />
        <ve-icon v-else name="filtergray" size="24" class="top-nav-filter__item-icon" />
        <text class="top-nav-filter__item-text">{{ item.label }}</text>
        <!-- moreFilter 显示 +? -->
        <view class="badge" v-if="key == 'moreFilter' && moreFilterSelectedNumber > 0">
          {{ `+${moreFilterSelectedNumber}` }}
        </view>
      </view>
    </block>
  </view>
</template>
<script lang="ts" setup>
  import { ref, computed, onMounted, reactive, watch, nextTick } from 'vue'
  import dayjs from 'dayjs'
  import { usePageDict } from '@/hooks/useDict'
  const dict = usePageDict('revenueSummary')
  const emits = defineEmits(['change'])

  // 资产-车系/车型收益排行会传入 revenueRankingTab
  const props = defineProps({
    // series | model
    revenueRankingTab: {
      type: String,
      default: '',
    },
  })

  // 顶部 tabsType
  // tabsType
  // total: 汇总
  // asset: 资产
  // income: 收入
  // expend: 支出
  const tabsType = ref('total')

  // queryParam
  const queryParam = ref({
    siteIdList: [],
    orgIdList: [],
    // 外部的时间
    outerStartTime: dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
    outerEndTime: dayjs().format('YYYY-MM-DD'),
    // 内部的时间
    innerStartTime: '',
    innerEndTime: '',
    orderTimeQueryType: 4,

    // 车系/车型
    seriesIdList: [],
    modelIdList: [],

    // 1:近7天 2:近一个月 3:日期选择
    selectDateType: 1,
  })

  // 外部选中的 selectDateType
  const outerSelectDateType = ref(1)

  // 切换 revenueRankingTab 时，清空已选车型、车型
  watch(
    () => props.revenueRankingTab,
    () => {
      // 清空 seriesIdList、modelIdList start
      queryParam.value.seriesIdList = []
      queryParam.value.modelIdList = []
      lastData.form = { ...queryParam.value }
      lastData.labelForm = {
        ...initData.labelForm,
        seriesIdList: '',
        modelIdList: '',
      }
      // 清空 seriesIdList、modelIdList end
      // 传递数据
      emitData()
    },
  )

  // 导航条
  const navList = reactive({
    last7Day: {
      label: '近7天',
      active: true,
    },
    last30Day: {
      label: '近一个月',
      active: false,
    },
    moreFilter: {
      label: '更多筛选',
      active: true,
    },
  })
  // 切换tabs
  const tabsChangeFn = (tab: string) => {
    // tabsType
    // total: 汇总
    // asset: 资产
    // income: 收入
    // expend: 支出
    // 如果当前是总支出，则对应行为是切换到其他tab，清空已选门店
    if (tabsType.value == 'expend') {
      // 清空已选门店
      queryParam.value.siteIdList = []
      queryParam.value.siteOrgIdList = []

      // 更新 lastData
      lastData.form = {
        ...lastData.form,
        siteIdList: '',
      }
      lastData.labelForm = {
        ...lastData.labelForm,
        siteIdList: '',
      }
    }
    // 如果目标是总支出，则对应行为是其他tab切换到总支出，设置 orgIdList 默认值
    if (tab == 'expend') {
      if (queryParam.value.siteOrgIdList && queryParam.value.siteOrgIdList.length > 0) {
        // 更新 orgIdList
        queryParam.value.orgIdList = [...queryParam.value.siteOrgIdList]

        // 更新 lastData
        lastData.form = { ...queryParam.value }
        lastData.labelForm = {
          ...initData.labelForm,
          orgIdList: lastData.labelForm.siteIdList,
        }
      }
    }

    // 更新更多筛选高亮状态
    nextTick(() => {
      navList.moreFilter.active = moreFilterSelectedNumber.value > 0
    })

    tabsType.value = tab
    // 传递数据
    emitData()
  }
  // 初始值
  const initData = {
    init: false,
    form: {},
    labelForm: {},
  }
  // 上一次的值
  const lastData = {
    form: {},
    labelForm: {},
  }
  // 资产-门店发生变化 更新 lastData
  const onAssetSiteChange = (val, options) => {
    let siteIdListLabel = ''
    if (options.length > 0) {
      const siteNameList = options.map((item) => item.siteName)
      siteIdListLabel = siteNameList.join(' | ')
    }
    lastData.form = { ...queryParam.value }
    lastData.labelForm = {
      ...initData.labelForm,
      siteIdList: siteIdListLabel,
    }
    emitData()
  }
  // 筛选点击事件
  const onFilterClick = (item: any, key: string) => {
    // 更多筛选
    if (key == 'moreFilter') {
      uni.navigateTo({
        url: '/pages/utils/moreFilter',
        events: {
          onConfirm: (val: any, label_form: any) => {
            lastData.form = {
              ...queryParam.value,
              ...val,
            }
            lastData.labelForm = { ...label_form }

            // 更新queryParam
            queryParam.value = {
              ...queryParam.value,
              ...val,
            }
            // emits('update:queryParam', val)
            // 处理近七天、近一个月高亮
            if (val.innerStartTime && val.innerEndTime) {
              queryParam.value.selectDateType = 3
              outerSelectDateType.value = 3

              navList.last7Day.active = false
              navList.last30Day.active = false
            } else {
              navList.last7Day.active = false
              navList.last30Day.active = false
              if (outerSelectDateType.value == 3 || outerSelectDateType.value == 1) {
                queryParam.value.selectDateType = 1
                outerSelectDateType.value = 1
                navList.last7Day.active = true

                // 外部的时间
                queryParam.value.outerStartTime = dayjs().subtract(6, 'day').format('YYYY-MM-DD')
                queryParam.value.outerEndTime = dayjs().format('YYYY-MM-DD')
              } else if (outerSelectDateType.value == 2) {
                queryParam.value.selectDateType = 2
                outerSelectDateType.value = 2
                navList.last30Day.active = true

                // 外部的时间
                queryParam.value.outerStartTime = dayjs().subtract(29, 'day').format('YYYY-MM-DD')
                queryParam.value.outerEndTime = dayjs().format('YYYY-MM-DD')
              }
            }
            // 更新更多筛选高亮状态
            nextTick(() => {
              navList.moreFilter.active = moreFilterSelectedNumber.value > 0
            })
            // 传递数据
            emitData()
          },
        },
        success: (res) => {
          // 传递数据
          res.eventChannel.emit('acceptDataFromOpenerPage', {
            searchList: searchList.value,
            queryParam: queryParam.value,
            initData,
            lastData,
          })
        },
      })
    } else {
      // 未激活态下
      if (!item.active) {
        navList.last7Day.active = false
        navList.last30Day.active = false
        item.active = true
        if (key == 'last7Day') {
          queryParam.value.outerStartTime = dayjs().subtract(6, 'day').format('YYYY-MM-DD')
          queryParam.value.outerEndTime = dayjs().format('YYYY-MM-DD')
          queryParam.value.selectDateType = 1
        }
        if (key == 'last30Day') {
          queryParam.value.outerStartTime = dayjs().subtract(29, 'day').format('YYYY-MM-DD')
          queryParam.value.outerEndTime = dayjs().format('YYYY-MM-DD')
          queryParam.value.selectDateType = 2
        }
        // 更新 lastData
        lastData.form = {
          ...queryParam.value,
          innerStartTime: '',
          innerEndTime: '',
        }
        // 内部时间清空
        queryParam.value.innerStartTime = ''
        queryParam.value.innerEndTime = ''
        // 更新外部的 outerSelectDateType
        outerSelectDateType.value = queryParam.value.selectDateType

        // 传递数据
        emitData()
      }
    }
  }

  // 定义 searchList 的类型
  interface SearchItem {
    prop: string | string[]
    label: string
    type: string
    attrs?: {
      mode?: string
      mustAll?: boolean
      options?: any[]
      show?: boolean
      multiple?: boolean
      type?: string
      label?: string // 明确 attrs 中可能包含 label
    }
  }

  const today = dayjs()
  const searchList = computed<SearchItem[]>(() => {
    return [
      {
        prop: ['innerStartTime', 'innerEndTime'],
        label: '时间',
        type: 'daterange-picker',
        attrs: {
          mode: 'date',
          mustAll: true,
          config: {
            start: {
              minDate: '2024-01-01 00:00:00',
              maxDate: today.add(180, 'day').format('YYYY-MM-DD 23:59:59'),
            },
            end: {
              minDate: '2024-01-01 00:00:00',
              maxDate: today.add(180, 'day').format('YYYY-MM-DD 23:59:59'),
            },
          },
        },
      },
      {
        prop: 'orderTimeQueryType',
        label: '订单取值',
        type: 'picker',
        attrs: {
          options: dict.orderQueryTypeEnums,
          show: tabsType.value != 'expend',
        },
      },
      {
        prop: 'siteIdList',
        label: '门店',
        type: 'remote-select',
        attrs: {
          show: tabsType.value != 'expend',
          multiple: true,
          type: 'site_all',
          title: '选择门店',
          params: {
            oldIdList: queryParam.value.siteOrgIdList,
          },
          changeWithOption: (_: any, options: any) => {
            // 营收汇总、总资产、总收入 记录 orgId
            if (tabsType.value != 'expend') {
              const orgIdList = []
              if (options.length) {
                const selectOrgIdList = options.map((item: any) => item.orgId)
                orgIdList.push(...selectOrgIdList)
              }
              queryParam.value.siteOrgIdList = orgIdList
            }
          },
        },
      },
      {
        prop: 'orgIdList',
        label: '门店',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'org_selectAuthListByOrgNameLike',
          title: '选择门店',
          show: tabsType.value == 'expend',
          params: {
            oldIdList: queryParam.value.siteOrgIdList,
          },
        },
      },
      {
        prop: 'seriesIdList',
        label: '车系',
        type: 'remote-select',
        attrs: {
          type: 'carSeries_tenant',
          multiple: true,
          show: props.revenueRankingTab == 'series',
        },
      },
      {
        prop: 'modelIdList',
        label: '车型',
        type: 'remote-select',
        attrs: {
          type: 'carModel_tenant',
          multiple: true,
          show: props.revenueRankingTab == 'model',
        },
      },
    ]
  })
  // 初始化
  const initDataFn = () => {
    // 防止页面操作queryParam 丢失筛选值，获取最新的queryParam
    lastData.form = { ...queryParam.value }
    if (initData.init) return
    initData.init = true
    // 初始化form 和labelForm
    initData.form = { ...queryParam.value }
    searchList.value.forEach((it) => {
      if (it.attrs && it.attrs.label) {
        initData.labelForm[it.prop] = it.attrs.label
      }
    })
    lastData.form = { ...queryParam.value }
    lastData.labelForm = { ...initData.labelForm }
  }
  // 初始化数据
  initDataFn()
  // 更多筛选已选条件数量
  const moreFilterSelectedNumber = computed(() => {
    let selNumber = 0
    // 订单取值默认有值，不存在无值情况
    if (tabsType.value != 'expend') {
      selNumber += 1
    }
    // 时间
    if (queryParam.value.innerStartTime && queryParam.value.innerEndTime) {
      selNumber += 1
    }
    // 机构
    if (tabsType.value == 'expend') {
      if (queryParam.value.orgIdList && queryParam.value.orgIdList.length > 0) {
        selNumber += 1
      }
    } else {
      // 门店
      if (queryParam.value.siteIdList && queryParam.value.siteIdList.length > 0) {
        selNumber += 1
      }
    }
    // 资产-车系/车型收益排行
    if (props.revenueRankingTab == 'series' && queryParam.value.seriesIdList.length > 0) {
      selNumber += 1
    }
    if (props.revenueRankingTab == 'model' && queryParam.value.modelIdList.length > 0) {
      selNumber += 1
    }
    return selNumber
  })
  // 传递数据
  const emitData = () => {
    const params = queryParam.value
    let emitParam = {
      // 门店
      siteIdList: params.siteIdList,
      // 机构
      orgIdList: params.orgIdList,
      // 时间
      startTime: params.innerStartTime || params.outerStartTime,
      endTime: params.innerEndTime || params.outerEndTime,
      // 订单取值
      orderTimeQueryType: params.orderTimeQueryType,
      // 车系列表
      seriesIdList: [],
      // 车型列表
      modelIdList: [],
      // 时间类型
      selectDateType: params.selectDateType,
    }
    if (['series', 'model'].includes(props.revenueRankingTab)) {
      // 删除门店列表
      delete emitParam.siteIdList
      // 资产-车系/车型收益排行
      if (props.revenueRankingTab == 'series') {
        emitParam.seriesIdList = queryParam.value.seriesIdList
      }
      if (props.revenueRankingTab == 'model') {
        emitParam.modelIdList = queryParam.value.modelIdList
      }
    }
    emits('change', emitParam)
  }
  onMounted(() => {
    emitData()
  })

  defineExpose({
    tabsChangeFn,
  })
</script>
<style lang="less" scoped>
  .top-nav-filter {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10rpx;
    &__item {
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid #dadbdd;
      border-radius: 4px;
      font-weight: 400;
      font-size: 24rpx;
      color: #8491a8;
      &-icon {
        margin-right: 8rpx;
      }
      .badge {
        height: 24rpx;
        line-height: 24rpx;
        font-size: 22rpx;
        margin-left: 8rpx;
        padding: 0 8rpx;
        color: #3072f6;
        background: #ffffff;
        border-radius: 12rpx 12rpx 12rpx 12rpx;
      }
    }
  }
  .active {
    border-color: #3072f6;
    color: #fff;
    background: #3072f6;
    .top-nav-filter__item-icon {
      color: #fff;
    }
  }
</style>
